<template>
  <div class=''>
    <!-- 面包屑导航区域 -->
    <Bootstrap v-bind:BootstrapTitle="BootstrapTitle"></Bootstrap>
    <!-- 卡片内容 -->
    <el-card class="box-card">
      <!-- 搜索 -->

      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="warning" @click="dialogVisible = true">添加用户</el-button>
          <!-- 对话框 -->
          <!-- 添加用户 -->
          <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="addFomeRemove">
            <el-form :model="addForm" :rules="addRules" ref="addruleFormRef" label-width="70px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="addForm.phone"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>

        </el-col>
        <!-- 修改 -->
        <el-dialog @close="modifyUserss" title="修改用户信息" :visible.sync="modifydialogVisible" width="30%">
          <el-form :model="modifyUserList" :rules="addRules" ref="modifyUserListRes" label-width="100px"
            class="demo-ruleForm">
            <el-form-item label="用户名">
              <el-input disabled v-model="modifyUserList.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="modifyUserList.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="modifyUserList.phone"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="modifydialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="modifyaddUser">确 定</el-button>
          </span>
        </el-dialog>
        </el-col>

      </el-row>
      <!-- 角色分配对话框 -->
      <el-dialog title="角色分配" :visible.sync="UserdialogVisible" width="30%" @close="setUserDialogClose">
        <div>
          <p>当前用户:{{allotInfo.username}}</p>
          <p>当前角色:{{allotInfo.role_name}}</p>
          <p>分配新角色:
            <el-select v-model="allotId" placeholder="请选择">
              <el-option v-for="item in allotList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="UserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 对话框end -->
      <!-- 表单 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index" label="" width="50">
        </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" active-color="#ffcc33" inactive-color="#909399"
              @change="switchChang(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyUser(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="DeleteUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-help" size="mini" @click="allotUser(scope.row)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>

      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[2, 4, 6, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="totla">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
import Bootstrap from "../../component/component/Bootstrap";
export default {
  name: "",
  components: {
    Bootstrap,
  },
  data() {
    // 校验邮箱
    var checkEmail = (rule, value, cb) => {
      const reg = new RegExp(
        "^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$"
      );
      if (reg.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 校验手机号
    var checkPhone = (rule, value, cb) => {
      const regPhone = new RegExp(
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      );
      if (regPhone.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      BootstrapTitle: {
        first: "用户管理",
        second: "/users",
        third: " 用户列表",
      },
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      userList: [],
      modifyUserList: {
        name: "",
        email: "",
        phone: "",
      },
      allotInfo: {},
      allotId: "",
      allotList: [],
      totla: 0,
      dialogVisible: false,
      delitedialogVisible: false,
      modifydialogVisible: false,
      UserdialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        phone: "",
      },
      modifyUserListRules: {},
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },

          { validator: checkEmail, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },

          { validator: checkPhone, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //  获取用户列表数据
    async getUserList() {
      let res = await this.$http.get("users", { params: this.queryInfo });
      // console.log(res, res);
      if (res.data.meta.status !== 200)
        return this.$message.erroe("数据获取失败");
      this.$message({
        message: res.data.meta.msg,
        type: "success",
      });
      this.userList = res.data.data.users;
      this.totla = res.data.data.total;
    },
    async getUserState(id, type) {
      let res = await this.$http.put(`users/${id}/state/${type}`);
      if (res.data.meta.status !== 200)
        return this.$message.error("res.data.meta.msg");
      this.$message({
        message: res.data.meta.msg,
        type: "success",
      });
    },

    // 监听条数
    handleSizeChange(size) {
      //console.log(size, "size");
      this.queryInfo.pagesize = size;
      this.getUserList();
    },
    // 监听页数
    handleCurrentChange(page) {
      // console.log(page, "page");
      this.queryInfo.pagenum = page;
      this.getUserList();
    },
    // 用户状态
    switchChang(userState) {
      // console.log(userState, "userState");
      let id = userState.id;
      let type = userState.mg_state;
      this.getUserState(id, type);
    },
    // 监听关闭对话框
    addFomeRemove() {
      this.$refs.addruleFormRef.resetFields();
    },
    // 表单预验证
    addUser() {
      // console.log(this.addForm);
      this.$refs.addruleFormRef.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        let res = await this.$http.post("users", this.addForm);
        // console.log(res);
        if (res.data.meta.status !== 201) {
          return this.$message.error(res.data.meta.msg);
        } else {
          this.$message.success(res.data.meta.msg);
        }

        // 隐藏对话框
        this.dialogVisible = false;
        this.getUserList();
      });
    },

    // 删除用户资料
    DeleteUser(id) {
      this.$confirm("此操作将永久删除该用户信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$http.delete("users/" + id);
          console.log(res, "res");
          if (res.data.meta.status !== 200) {
            this.$message.error("删除用户信息失败");
          } else {
            this.getUserList();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            return;
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改用户资料
    async modifyUser(id) {
      // console.log(id, "id");
      this.modifydialogVisible = true;
      window.sessionStorage.setItem("id", id);
      let res = await this.$http.get("users/" + id);
      // console.log(res);
      if (res.data.meta.status !== 200)
        return this.$message.error(res.data.meta.msg);
      this.$message.success(res.data.meta.msg);
      this.modifyUserList.name = res.data.data.username;
      this.modifyUserList.email = res.data.data.email;
      this.modifyUserList.phone = res.data.data.mobile;
      // console.log(res.data.data);
    },
    modifyUserss() {
      this.$refs.modifyUserListRes.resetFields();
      sessionStorage.removeItem("id");
    },
    // 修改预验证
    modifyaddUser() {
      this.$refs.modifyUserListRes.validate(async (valid) => {
        // console.log(valid);
        if (!valid) return;
        let id = window.sessionStorage.getItem("id");
        // console.log(id, "id");
        this.getmodifyUser(
          id,
          this.modifyUserList.email,
          this.modifyUserList.phone
        );

        // 隐藏对话框
        this.modifydialogVisible = false;
        this.getUserList();
      });
    },
    async getmodifyUser(id, email, mobile) {
      let res = await this.$http.put("users/" + id, { email, mobile });
      // console.log(res, "303");
      if (res.data.meta.status !== 200) {
        return this.$message.error(res.data.meta.msg);
      } else {
        this.$message.success(res.data.meta.msg);
      }
    },
    async allotUser(UserInfo) {
      this.allotInfo = UserInfo;
      // console.log(this.allotInfo);
      this.UserdialogVisible = true;
      const res = await this.$http.get("roles");
      if (res.data.meta.status != 200)
        return this.$message.erroe(res.data.meta.msg);
      this.$message.success(res.data.meta.msg);
      this.allotList = res.data.data;
      // console.log(res, "resres");
    },
    // 点击按钮修改角色
    async saveRoleInfo() {
      if (this.allotId == "") {
        return this.$message.error("请分配新角色");
      }

      const res = await this.$http.put(`users/${this.allotInfo.id}/role`, {
        rid: this.allotId,
      });
      // console.log(res, "res");
      if (res.data.meta.status !== 200) {
        this.UserdialogVisible = false;
        return this.$message.error(res.data.meta.msg);
      } else {
        this.UserdialogVisible = false;
        this.$message.success(res.data.meta.msg);
      }
    },
    setUserDialogClose() {
      this.allotId = "";
      this.allotInfo = {};
    },
  },
};
</script>
<style lang='less' scoped>
</style>